<template>
	<view class="container">
		<view class="step_one">
			<view class="popup_group">
				<view class="popup_group_item">
					<view class="popup_group_item_label">年票名称</view>
					<view class="popup_group_item_value"><input v-model="setFormData.store_name" type="text" maxlength="9" value="" placeholder="年票名称" /></view>
				</view>
				
				<view class="popup_group_item">
					<view class="popup_group_item_label">绑定钓塘</view>
					<view class="popup_group_item_value">
						<picker @change="pondPickerChange" :value="pondIndex" :range="ponds" range-key="storeName">
							<view class="uni-input">{{ponds[pondIndex].storeName}}</view>
						</picker>
					</view>
				</view>
				
				<view class="popup_group_item">
					<view class="popup_group_item_label">库存</view>
					<view class="popup_group_item_value"><input v-model="setFormData.yearlyYpStock" type="number" maxlength="5" placeholder="年票库存" /></view>
				</view>
				
				<view class="popup_group_item">
					<view class="popup_group_item_label">价格（元）</view>
					<view class="popup_group_item_value"><input v-model="setFormData.yearlyYpPrice" type="digit" maxlength="5" placeholder="请输入年票价格" /></view>
				</view>
				
			</view>

			<view class="input_content">
				<view class="input_content_describe" style="border-top: 0px;">
					<view class="input_content_describe_title">
						<view class="input_content_describe_title_msg">简介</view>
						<view class="input_content_describe_title_num">
							<text v-if="setFormData.store_info">{{ setFormData.store_info.length }}</text>
							<text v-else>0</text>
							/200
						</view>
					</view>
					<view class="input_content_describe_textarea">
						<textarea v-model="setFormData.store_info" value="" placeholder="请填写简介信息" placeholderClass="placeholderClass" maxlength="200" />
					</view>
				</view>
				
				<view class="photo_count">
					<text class="photo_size">添加主图和轮播图，第1张作为主图。建议：图片尺寸为750*750px</text>
					<view class="input_content_photo">
						<view class="input_content_photo_adPh" v-for="(item, index) in setFormData.imageList" :key="index">				
							<image :src="item" class="myimg2 photos"></image>  			
							<view class="input_content_photo_adPh_jiao" @click="deleteImage(index)"><image src="../static/images/close.png" mode=""></image></view>
						</view>
						<view v-if="setFormData.imageList.length < 9" class="input_content_photo_adPh addBtn" @click="clk">
							<view><image src="../static/images/creamer.png" mode="widthFix"></image></view>
							<view>添加图片</view>
						</view>
					</view>
				</view>
			</view>			
		</view>

		<view class="handle dobuButton">
			<view class="handle_button" @click="doSubmit">提交</view>
		</view>
		
		<avatar @upload="doUpload" quality="1" ref="avatar" selWidth="250upx" selHeight="250upx"></avatar>
	</view>
</template>

<script>
const app = getApp();
import { navigateTo, serialize, setStorage, getStorage, removeStorage, Loading, hideLoading, Modal } from '../../../libs/uniApi.js';
import { categoryBrandlist, categorySelect, categoryList, attrList, templateList, productDetail, getDeliveryType } from '@/api/product.js';
import platfrom from '../components/platform.vue';
import storeClassification from '../components/store_classification.vue';
import avatar from "@/components/yq-avatar/yq-avatar.vue";
import {TOKENNAME, HTTP_REQUEST_URL} from '@/config/app.js';
import store from '@/store';
import { productCreate, productUpdate } from 'api/product.js';
import {genDefaultPartition, correctSeats, MyTip} from '../../../components/ssty/common.js';

import {queryGoodsByFshGround} from '@/api/fsh.js'

export default {
	data() {
		
		return {
			merId: '',
			product_id: '', // 商品Id
			disModel: false,
			upload_max: 10,
			uploadUrl: `${HTTP_REQUEST_URL}/api/upload/video`,
			setFormData: {
				imageList: [],
				image: '', //主图
				slider_image: '', // 轮播图
				store_name: '', // 商品名
				store_info: '', // 简介
				
				is_good: 0, // 是否推荐
				is_gift_bag: 0,
				sort: '',
				once_count: '1', // 限购数量
				video_link: '',
				
				yearlyYpPrice: undefined, // 价格
				yearlyYpStock: undefined, // 库存
				bindPondId: undefined,   // 绑定钓塘id
				bindPondName: undefined, // 绑定钓塘名称
			},
			
			ponds: [],
			pondIndex: 0, 	// 绑定钓塘
		};
	},
	onLoad(opt) {
		this.merId = opt.mer_id;
		this.product_id = opt.product_id;

		if(getStorage('goodsDis')) { // 商品详情和普通商品共用一个页面
			this.disModel = true;
		}
		
		// 查询商品列表
		queryGoodsByFshGround(this.merId, 1).then(res=>{
			this.ponds = [{productId:0, storeName:'请选择年票要绑定的钓塘'}, ...res.entity];
			
			if (this.product_id)
				this.loadDataFromSrv(); 	// 编辑
			else
				this.loadDataFromStorage(); // 新建
				
		}).catch(e=>{
			console.error(e);
			MyTip("查询钓塘失败，请稍后重试");
		});
	},
	onShow() {
	},

	watch: {
		setFormData: {
			handler(val) {
				console.log("watch setFormData: %o", val);
				setTimeout(()=>{
					setStorage('addGoodsFormData', this.setFormData);
				});
			},
			deep: true
		},
		'setFormData.imageList'(val) {
			this.setFormData.image = val.length ? val[0] : '';
			this.setFormData.slider_image = val.length ? serialize(val).splice(1) : [];
		}
	},
	methods: {
		
		// 获取数据
		async loadDataFromStorage() {
			if (getStorage('addYearlyYpFormData')) {
				this.setFormData = getStorage('addYearlyYpFormData');
			}
		},
		// 查询详情数据
		loadDataFromSrv() {
			Loading();
			
			if(getStorage('editYearlyYpFormData')) {
				removeStorage('editYearlyYpFormData'); 
			}
			
			productDetail(this.merId, this.product_id).then(res => {
				setStorage('editYearlyYpFormData', res.data);
				let editYearlyYpFormData = res.data;
				Object.keys(this.setFormData).forEach(item => {
					this.setFormData[item] = editYearlyYpFormData[item];
				});
				this.setFormData.product_id = this.product_id;
				this.setFormData.imageList = [...(this.setFormData.image ? [this.setFormData.image] : []), ...this.setFormData.slider_image];
				
				this.setFormData.yearlyYpPrice = parseFloat(res.data.yp.yearlyYpPrice);
				this.setFormData.yearlyYpStock = parseFloat(res.data.stock);
				this.setFormData.bindProdId = res.data.yp.bindProdId;
				
				if(this.ponds.length > 1) {
					let i = this.ponds.findIndex(a=>a.productId == this.setFormData.bindProdId);
					if(i > 0) 
						this.pondIndex = i;
					else
						this.pondIndex = 0;
				}
				
				if(res.data.content && (res.data.content.title || res.data.content.image)) {
					setStorage('goodsDis', {store_name: res.data.content.title, imageList:res.data.content.image});
					this.disModel = true;
				}
				
				hideLoading();
			}).catch(e => {
				hideLoading();
				MyTip('加载失败，请稍后重试');
			});
		},
		
		pondPickerChange(e) {
			this.pondIndex = e.target.value;
			
			this.setFormData.bindProdId = this.ponds[this.pondIndex].productId;
			this.setFormData.bindProdName = this.ponds[this.pondIndex].storeName;			
		},
		
		
		// 选择图片
		handleChooseImage() {
			let that = this;
			that.$util.uploadImageOne('upload/image', function(res) {
				that.setFormData.imageList.push(res.data.path);
				
			});
		},
		clk() {
			let avatar = this.$refs.avatar;
			avatar.fChooseImg(1,{selWidth: '350upx', selHeight: '350upx', inner: true});
		},
		doUpload(rsp) {
			let that = this
			console.log(rsp);	
			
		
			uni.uploadFile({
				url: HTTP_REQUEST_URL + '/api/upload/image/field',
				filePath: rsp.path,
				name: 'field',
				formData: {
					'filename': rsp.path
				},
				header: {
					// #ifdef MP
					"Content-Type": "mulMyTipart/form-data",
					// #endif
					[TOKENNAME]: 'Bearer ' + store.state.app.token
				},
				success: (uploadFileRes) => {
					console.log(uploadFileRes.data);
					let imgData = JSON.parse(uploadFileRes.data)
					that.setFormData.imageList.push(imgData.data.path)
				},
				complete(res) {
					console.log(res)
				}
			});		
		},
		// 删除图片
		deleteImage(index) {
			this.setFormData.imageList.splice(index, 1);
		},
		
		// 是否推荐
		isGood(e) {
			this.setFormData.is_good = e.detail.value ? 1: 0;
		},
		// 是否开启礼包
		isGiftBag(e) {
			this.setFormData.is_gift_bag = e.detail.value ? 1: 0;
		},
		
		switchChange(value, item) {
			this.setFormData[item.model] = value ? 1 : 0;
		},
		// 跳转商品详情
		inputGoodsDetils() {
			navigateTo(1, '/pages/product/addGoods/addGoodDetils', { mer_id: this.merId });
		},
		// 上传视频
		uploadVideo() {
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				success: res => {
					if (Math.ceil(res.size / 1024) < this.upload_max * 1024) {
						uni.uploadFile({
							url: this.uploadUrl, //仅为示例，非真实的接口地址
							filePath: res.tempFilePath,
							name: 'file',
							//请求参数
							formData: {
								user: 'test'
							},
							header: {
								// #ifdef MP
								'Content-Type': 'mulMyTipart/form-data',
								// #endif
								[TOKENNAME]: 'Bearer ' + store.state.app.token
							},
							success: uploadFileRes => {
								let data = JSON.parse(uploadFileRes.data);
								this.setFormData.video_link = (data.data.src);
							},
							complete: a => {
								// console.log(a);
							}
						});
					} else {
						uni.showModal({
							title: '提示',
							content: `视频超出限制${this.upload_max}MB,已过滤`
						});
					}
				},
				fail: err => {
					uni.showModal({
						content: JSON.stringify(err)
					});
				}
			});
		},
		deleteVideo(index) {
			this.setFormData.video_link = '';
		},
		
		check() {
			console.log("check, setFormData: %o", this.setFormData)
			
			if(!this.pondIndex) {
				MyTip('请输入年票绑定的钓塘');
				return false;
			}
			let requireData = {
				image: '请选择主图', 
				store_name: '请输入年票名称',
				yearlyYpPrice: '请输入价格',
				yearlyYpStock: '请输入年票库存',
			};
			if(Object.keys(requireData).some(item => {
				if (!this.setFormData[item]) {
					MyTip(requireData[item]);
					return true;
				}
			}))
				return false;
			
			return true;
		},
		
		doSubmit() {
			if(!this.check()) {
				return;
			}
				
			this.setFormData.maxWeightPerFsh = parseFloat(this.setFormData.maxWeightPerFsh);
			this.setFormData.minWeightPerFsh = parseFloat(this.setFormData.minWeightPerFsh);
			
			let waitDeleteData = ['addYearlyYpFormData', 'editYearlyYpFormData', 'goodsDis']; // 提交后就把本地缓存数据清空
				
			let postData = {
				...getStorage('addGoodsFormData'),
				...this.setFormData,
				content: {
					title: getStorage('goodsDis') ? getStorage('goodsDis').store_name : '',
					image: getStorage('goodsDis') ? getStorage('goodsDis').imageList : []
				},
				video_link: this.setFormData.video_link,
				cate_id: app.globalData.race_cate,
			};
			
			if (this.product_id) {
				uni.showLoading({
					title: '正在修改中...'
				});
				productUpdate(this.merId, this.product_id, postData)
					.then(res => {
						hideLoading()
						waitDeleteData.forEach(item => {
							if (getStorage(item)) {
								removeStorage(item);
							}
						});
						
						console.log("ypIndex::doSubmit| productUpdate success");
						Modal('提交成功，等待平台审核', '点击确定，返回商品管理', {
							showCancel: false
						}).then(() => {
						uni.redirectTo({
							url:'/pages/product/goodsOnSale/index?mer_id=' + this.merId
						})
						})
					})
					.catch(errMsg => {
						uni.hideLoading();
						console.log("ypIndex::doSubmit| productUpdate fail", errMsg);
						MyTip(errMsg);
					});
			} else {
				uni.showLoading({
					title: '正在创建中...'
				});
				productCreate(this.merId, postData)
					.then(res => {
						hideLoading();
						
						waitDeleteData.forEach(item => {
							if (getStorage(item)) {
								removeStorage(item);
							}
						});
						
						console.log("ypIndex::doSubmit| productCreate success");
						Modal('提交成功，等待平台审核', '点击确定，返回商品管理', {
							showCancel: false,
						}).then(() => {
							uni.redirectTo({
								url:'/pages/product/goodsOnSale/index?mer_id=' + this.merId
							})
						})
					})
					.catch(errMsg => {
						hideLoading();
						console.log("ypIndex::doSubmit| productCreate false", errMsg);
						MyTip(errMsg);
					});
			}
		},
	}
};
</script>

<style lang="scss" scoped>
@import './scss/index.scss';

.content_list {
	width: 710rpx;
	margin: auto;
	padding: 0 20rpx;
	box-sizing: border-box;
	background: #fff;
	margin-top: 31rpx;
	border-radius: 10rpx;
	.content_list_item {
		padding: 32rpx 10rpx;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #eee;
		.content_list_item_han {
			color: #bbbbbb;
			display: flex;
			align-items: center;
		}
	}
	.content_list_video {
		min-height: 154rpx;
		padding: 23rpx 10rpx;
		display: flex;
		justify-content: space-between;
		.content_list_video_title {
			padding-top: 10rpx;
		}

		.video_list {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			flex-wrap: wrap;
		}
	}
}

.photo {
	border: 1px solid #dddddd;
	opacity: 1;
	border-radius: 8rpx;
	font-size: 28rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	text-align: center;
	// padding: 27rpx 21rpx 24rpx 21rpx;
	width: 150rpx;
	height: 150rpx;
	box-sizing: border-box;
	color: #bbbbbb;
	margin-left: 16rpx;
	position: relative;
	margin-bottom: 12rpx;
	image {
		width: 62rpx;
		margin-bottom: 10rpx;
	}
}

.jiao {
	image {
		position: absolute;
		top: -14rpx;
		right: -14rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		padding: 8rpx;
		background: #e93323;
		z-index: 999;
	}
	video {
		width: 150rpx;
		height: 150rpx;
	}
}
.container_input {
	background: #fff;
	padding: 0 20rpx;
	width: 710rpx;

	margin: auto;
	margin-top: 31rpx;
	border-radius: 10rpx;
	&_item {
		display: flex;
		height: 106rpx;
		align-items: center;
		.select_and_input {
			display: flex;
			align-items: center;
			justify-content: space-between;
			.greyColor {
				color: #bbbbbb;
			}
		}

		.radio {
			padding: 30rpx 0;
		}

		&_label {
			padding-left: 10rpx;
			color: #333333;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			.select_check {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 40rpx;
				height: 40rpx;
				border: 1px solid #cccccc;
				border-radius: 50%;
				margin-right: 20rpx;

				.iconfont {
					font-size: 24rpx;
				}
			}

			.select {
				background: #e93323;
				border: none;
				.iconfont {
					color: #fff;
				}
			}
		}
		&_value {
			padding-right: 10rpx;
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			> span:nth-child(1) {
				display: inline-block;
				margin-right: 15rpx;
			}
			.text {
				color: #000;
				display: inline-block;
				max-width: 400rpx;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			input {
				text-align: right;
			}

			.select_group {
				display: flex;
			}

			&_select {
				display: flex;
				margin-right: 110rpx;
			}
		}

		.flex_start {
			padding: 0 10rpx;
			margin-top: 40rpx;
			justify-content: flex-start;
		}
	}
	> view:not(:last-child) {
		border-bottom: 1px solid #eeeeee;
	}
}

.inputPlaceHolder {
	color: #bbbbbb;
}

.paddingTop_none {
	padding-top: 0 !important;
}
.marginTop_none {
	margin-top: 0;
}

</style>
